<template>
  <el-popover
      ref="popover"
      placement="right"
      width="400"
      @hide="close"
      trigger="click">
    <div>
      <el-table :data="tableData" width="100%">
        <el-table-column property="field" label="field"></el-table-column>
        <el-table-column  property="alias" label="alias">
          <template slot-scope="scope">
            <el-input v-model="scope.row.alias"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span style="float: right;margin-top: 15px">
        <el-button @click="cancel" size="small">Cancel</el-button>
      <el-button @click="submit" size="small" type="primary">Confirm</el-button>
      </span>
    </div>
    <el-button slot="reference" type="text" icon="el-icon-setting" style="font-size: 18px"></el-button>
  </el-popover>
</template>

<script>
export default {
  name: "aggregatesAlias",
  props: {
    value: {
      type: Array,
      default: function () {
        return []
      }
    },
    aggregatesArr: {
      type: Array,
      default: function () {
        return []
      }
    }
  },
  data () {
    return {
      tableData: []
    }
  },
  watch: {
    value: {
      handler (val) {
        this.tableData = val.map(item => {
          return {
            field: item,
            alias: this.getAlias(item)
          }
        })
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    getAlias (field) {
      const item = this._.find(this.aggregatesArr, {field})
      return item ? item.alias : field
    },
    submit () {
      this.$emit('submit', this.tableData)
      this.$refs.popover.doClose()
    },
    cancel () {
      this.$refs.popover.doClose()
    },
    close () {
      this.tableData = this.value.map(item => {
        return {
          field: item,
          alias: this.getAlias(item)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>